package com.njd.test.autocreatedentity;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.DbKit; 

public class AutoCreatedEntityName {

	public AutoCreatedEntityName() {

	}

	/***
	 * 生成表实体
	 */
	@SuppressWarnings("rawtypes")
	private String getEntity(String tableName, Map<String,String> property,String packagename) {
		String ln = "\r\n";
		StringBuffer sb = new StringBuffer();
		sb.append(ln+"\t/***\t\r\n\t*表名："+tableName+"\t\r\n\t*/");
		sb.append(ln + "\tpublic static final class " + FileNameManager.CamelCase(tableName.split("_")) + "{" + ln);
		sb.append("\t\tpublic static final String " + "tableName" + "=\"" + tableName+ "\";" + ln);
		Iterator i=property.entrySet().iterator();
		while(i.hasNext()){
			Map.Entry e=(Map.Entry)i.next();
			sb.append("\t\tpublic static final String "
					+ FileNameManager.CamelCase(e.getKey().toString().split("_")) + "=\"" + e.getKey().toString()
					+ "\";" + ln);
		}
		sb.append("\t\tpublic static final String[] all={");
		
		Iterator is=property.entrySet().iterator();
		while(is.hasNext()){
			Map.Entry e=(Map.Entry)is.next();
			sb.append("\r\n\t\t\t");
			sb.append(FileNameManager.CamelCase(e.getKey().toString().split("_")));
			sb.append(",");
		}
		sb.deleteCharAt(sb.length()-1);;
		sb.append("\r\n\t\t};\r\n");
		sb.append("\t\tpublic static final Integer size=" + property.size() + ";"
				+ ln);
		sb.append("\t}" + ln);
		try {
			new AutoCreatedModelFile(FileNameManager.CamelCase(tableName.split("_")),property,packagename);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private String CreatedRFile(Map<String,Map<String,String>> map,String packagename)
	{
		
		String ln = "\r\n";
		StringBuffer sb = new StringBuffer();
		sb.append(ln +"package "+packagename+";"+ln+
						"/***"+ln+
						" * 表文件结构。"+ln+
						" * 对应表文件名。"+ln+
						" * 在Model中不需要记住对应的表名。"+ln+
						" * 只用此文件中对应的名称。"+ln+
						" * 同时避免了字段名修改，删除后程序结构破坏。"+ln+
						" * @author 石啸天"+ln+
						" *"+ln+
						" */"+ln+
						"public final class R {"+ln
						);
		
		Iterator i=map.entrySet().iterator();
		while(i.hasNext()){//只遍历一次,速度快
		Map.Entry e=(Map.Entry)i.next();
		sb.append(getEntity(e.getKey().toString(),(Map<String,String>)e.getValue(),packagename));
		}
		sb.append(ln + "}");
		return sb.toString();
	}
	/***
	 * 读取数组中全部的数据表生成对应R文件
	 * @param tableName 表名数组
	 */
	public void created(String[] tableName,String packagename) {
		DataBeasTypeToJavaType dtj=new DataBeasTypeToJavaType();
		System.out.println("开始生成实体R文件");
		Connection conn = null;
		PreparedStatement colunmsPs = null;
		Map<String,Map<String,String>> all = new HashMap<String,Map<String,String>>();
		try {
			conn = DbKit.getConfig().getConnection();
			for(int i=0;i<tableName.length;i++){
			colunmsPs = conn.prepareStatement("desc " + tableName[i]);
			//字段列表
			Map<String,String> colunms = new HashMap<String,String>();
			ResultSet columnsRs = colunmsPs.executeQuery();
			// 获取对应表中的字段
			while (columnsRs.next()) {
//				colunms.add(columnsRs.getString(1));
//				System.out.println("字段   "+columnsRs.getString(1)+" "+columnsRs.getString(2).split(")")[0]);
				colunms.put(columnsRs.getString(1),dtj.get(columnsRs.getString(2).split("\\(")[0]));
			}
			System.out.println("表为 " + FileNameManager.CamelCase(tableName[i].split("_")));
			all.put(tableName[i],colunms);
			colunmsPs.close();
			}
			conn.close();
//			System.out.println(CreatedRFile(all,packagename));
			System.out.println(packagename);
			String[] pn=packagename.split("\\.");
//			System.out.println(pn[0]);
			StringBuffer file=new StringBuffer();
			String dir=JFinal.me().getServletContext().getRealPath("/");
			file.append(dir.substring(0, dir.length()-7)+"src");
			for(String p:pn)
			{
				file.append("\\");
				file.append(p);
			} 
			System.out.println(file.toString());
			FileWriter fileWriter=new FileWriter(file.toString()+"/"+"R.java");
			fileWriter.write(CreatedRFile(all,packagename));
			fileWriter.flush();
			fileWriter.close();
			System.out.println("生成完成");
//			return getEntity(tableName, property);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			return null;
		}

	}
	
}